package com.bnlr.lrparking.appui.carplace;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.appui.web.WebActivity;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.util.BitmapHelper;
import com.bnlr.lrparking.event.PaySucceeEvent;
import com.bnlr.lrparking.model.AddCarPlaceBean;
import com.bnlr.lrparking.model.CarTypeBean;
import com.bnlr.lrparking.model.UpImgM;
import com.bnlr.lrparking.model.UploadGoodsBean;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.util.Config;
import com.bnlr.lrparking.util.DbTOPxUtils;
import com.bnlr.lrparking.util.MyGridView;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.zzti.fengyongge.imagepicker.PhotoPreviewActivity;
import com.zzti.fengyongge.imagepicker.PhotoSelectorActivity;
import com.zzti.fengyongge.imagepicker.model.PhotoModel;
import com.zzti.fengyongge.imagepicker.util.CommonUtils;
import com.zzti.fengyongge.imagepicker.util.FileUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hp on 2017/9/4.
 * 添加车位 -- 选择图片
 */

public class SelectPhotoActivity extends BaseActivity {

    private TextView tvNavTitle,tv_clause;
    private TextView tv_selectphoto_btn;
    private MyGridView stall_GV,file_stall_GV;
    private List<PhotoModel> single_photos = new ArrayList<PhotoModel>();
    private ArrayList<UploadGoodsBean> img_uri = new ArrayList<UploadGoodsBean>();
    private ArrayList<UploadGoodsBean> file_uri = new ArrayList<UploadGoodsBean>();
    private int screen_widthOffset;
    private GridImgAdapter gridImgsAdapter;
    private GridFileAdapter gridFileAdapter;
    private String path = "";
    private String path2 = "";
    private AddCarPlaceBean bean;
    private List<String> urlArray= new ArrayList<>();
    private List<String> fileArray = new ArrayList<>();
    private String upTag ="1";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_selectphoto);
        initView();
    }

    private void initView(){
        Intent intent = getIntent();
        bean = (AddCarPlaceBean) intent.getSerializableExtra("submit_info");
        tvNavTitle = (TextView) findViewById(R.id.tv_nav_title);
        tvNavTitle.setText("添加车位");
        stall_GV=(MyGridView)findViewById(R.id.stall_GV);
        file_stall_GV=(MyGridView)findViewById(R.id.file_stall_GV);
        tv_clause=(TextView)findViewById(R.id.tv_clause);
        tv_clause.setOnClickListener(this);
        tv_selectphoto_btn=(TextView)findViewById(R.id.tv_selectphoto_btn);
        tv_selectphoto_btn.setOnClickListener(this);
        Config.ScreenMap = Config.getScreenSize(this, this);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        screen_widthOffset = (display.getWidth() - (3* DbTOPxUtils.dip2px(this, 2)))/3;
        gridImgsAdapter = new GridImgAdapter();
        gridFileAdapter = new GridFileAdapter();
        file_stall_GV.setAdapter(gridFileAdapter);
        stall_GV.setAdapter(gridImgsAdapter);
        img_uri.add(null);
        file_uri.add(null);
        gridImgsAdapter.notifyDataSetChanged();
        gridFileAdapter.notifyDataSetChanged();

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.tv_clause:
                Intent intent=new Intent(baseContext,WebActivity.class);
                intent.putExtra("tag",3);
                startActivity(intent);
                break;
            case R.id.tv_selectphoto_btn:
                if (img_uri.get(0) == null) {
                    ToastUtils.showShort("车辆图片不能为空");
                    return;
                }
                if (file_uri.get(0) == null) {
                    ToastUtils.showShort("文件图片不能为空");
                    return;
                }

                String photoList = "";
                for (int i = 0; i < urlArray.size(); i++) {
                    photoList = photoList + urlArray.get(i) +",";
                }
                for (int i = 0; i < fileArray.size(); i++) {
                    photoList = photoList + fileArray.get(i) +",";
                }
                if (TextUtils.isEmpty(photoList)) {
                    return;
                }
                photoList = photoList.substring(0,photoList.length()-1);
                addStall(photoList);
                break;
        }
    }

    private void addStall(String photoList) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "AddNewSpace");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("number", bean.getPlaceNum());
            mRequest.add("spaceType", bean.getCarType());//
            mRequest.add("address",bean.getAddress());
            mRequest.add("areaId",bean.getAddressId());
            mRequest.add("parkName",bean.getPlaceName());
            mRequest.add("price",bean.getPrice());
            mRequest.add("phone",bean.getPhone());
            mRequest.add("photo",photoList);
            mRequest.add("tradeType",1);
            if (bean.getDescription() != null) {
                mRequest.add("description", bean.getDescription());
            }
            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<CarTypeBean>(baseContext, true, CarTypeBean.class) {
                        @Override
                        public void doWork(CarTypeBean data, String code) {

                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            if (TextUtils.equals("1", code)) {
                                EventBus.getDefault().post(new PaySucceeEvent());
                                finish();
                            } else {
                                try {
                                    CommonUtil.showToask(baseContext, obj.getString("msg"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                        }
                    }, true);

        } catch (Exception e) {

        }
    }


    class GridImgAdapter extends BaseAdapter implements ListAdapter {
        @Override
        public int getCount() {
            return img_uri.size();
        }
        @Override
        public Object getItem(int position) {
            return null;
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(SelectPhotoActivity.this).inflate(R.layout.activity_addstory_img_item, null);
           ViewHolder holder;
            if(convertView!=null){
                holder = new ViewHolder();
                convertView = LayoutInflater.from(SelectPhotoActivity.this).inflate(R.layout.activity_addstory_img_item,null);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            holder.add_IB = (ImageView) convertView.findViewById(R.id.add_IB);
            holder.delete_IV = (ImageView) convertView.findViewById(R.id.delete_IV);
            AbsListView.LayoutParams param = new AbsListView.LayoutParams(screen_widthOffset, screen_widthOffset);
            convertView.setLayoutParams(param);
            if (img_uri.get(position) == null) {
                holder.delete_IV.setVisibility(View.GONE);
                holder.add_IB.setImageResource(R.mipmap.addimg);
                holder.add_IB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        upTag = "1";
                        Intent intent = new Intent(SelectPhotoActivity.this, PhotoSelectorActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        intent.putExtra("limit", 3 - (img_uri.size() - 1));
                        startActivityForResult(intent, 1000);

                    }
                });
            } else {
                ImageLoader.getInstance().displayImage("file://" + img_uri.get(position).getUrl(), holder.add_IB);
                holder.add_IB.setImageResource(R.mipmap.addimg);
                holder.delete_IV.setOnClickListener(new View.OnClickListener() {
                    private boolean is_addNull;
                    @Override
                    public void onClick(View arg0) {
                        is_addNull = true;
                        String img_url = img_uri.remove(position).getUrl();
                        urlArray.remove(position);
                        for (int i = 0; i < img_uri.size(); i++) {
                            if (img_uri.get(i) == null) {
                                is_addNull = false;
                                continue;
                            }
                        }
                        if (is_addNull) {
                            img_uri.add(null);
                        }
                        FileUtils.DeleteFolder(img_url);//删除在emulate/0文件夹生成的图片
                        gridImgsAdapter.notifyDataSetChanged();
                    }
                });
                holder.add_IB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("photos",(Serializable)single_photos);
                        bundle.putInt("position", position);
                        bundle.putBoolean("isSave",false);
                        CommonUtils.launchActivity(SelectPhotoActivity.this, PhotoPreviewActivity.class, bundle);
                    }
                });

            }
            return convertView;
        }
        class ViewHolder {
            ImageView add_IB;
            ImageView delete_IV;
        }
    }
    class GridFileAdapter extends BaseAdapter implements ListAdapter {

        @Override
        public int getCount() {
            return file_uri.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(SelectPhotoActivity.this).inflate(R.layout.activity_addstory_img_item, null);
            GridFileAdapter.ViewHolder holder;
            if(convertView!=null){
                holder = new GridFileAdapter.ViewHolder();
                convertView = LayoutInflater.from(SelectPhotoActivity.this).inflate(R.layout.activity_addstory_img_item,null);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            holder.add = (ImageView) convertView.findViewById(R.id.add_IB);
            holder.delete = (ImageView) convertView.findViewById(R.id.delete_IV);
            AbsListView.LayoutParams param = new AbsListView.LayoutParams(screen_widthOffset, screen_widthOffset);
            convertView.setLayoutParams(param);
            if (file_uri.get(position) == null) {
                holder.delete.setVisibility(View.GONE);
                holder.add.setImageResource(R.mipmap.addimg);
                holder.add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        upTag = "2";
                        Intent intent = new Intent(SelectPhotoActivity.this, PhotoSelectorActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                        intent.putExtra("limit", 9 - (file_uri.size() - 1));
                        startActivityForResult(intent, 1001);

                    }
                });
            } else {
                ImageLoader.getInstance().displayImage("file://" + file_uri.get(position).getUrl(), holder.add);
                holder.add.setImageResource(R.mipmap.addimg);
                holder.delete.setOnClickListener(new View.OnClickListener() {
                    private boolean is_addNull;
                    @Override
                    public void onClick(View arg0) {
                        is_addNull = true;
                        String img_url = file_uri.remove(position).getUrl();
                        fileArray.remove(position);
                        for (int i = 0; i < file_uri.size(); i++) {
                            if (file_uri.get(i) == null) {
                                is_addNull = false;
                                continue;
                            }
                        }
                        if (is_addNull) {
                            file_uri.add(null);
                        }
                        FileUtils.DeleteFolder(img_url);//删除在emulate/0文件夹生成的图片
                        gridFileAdapter.notifyDataSetChanged();
                    }
                });
                holder.add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("photos",(Serializable)single_photos);
                        bundle.putInt("position", position);
                        bundle.putBoolean("isSave",false);
                        CommonUtils.launchActivity(SelectPhotoActivity.this, PhotoPreviewActivity.class, bundle);
                    }
                });

            }
            return convertView;
        }
        class ViewHolder {
            ImageView add;
            ImageView delete;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1000:
                if (data != null) {
                    List<String> paths = (List<String>) data.getExtras().getSerializable("photos");
                    if (img_uri.size() > 0) {
                        img_uri.remove(img_uri.size() - 1);
                    }
                    for (int i = 0; i < paths.size(); i++) {
                        img_uri.add(new UploadGoodsBean(paths.get(i), false));
                        //上传参数
                        path = path +CommonUtil.bitmapToBase64(BitmapHelper.getImage(paths.get(i), 200))
                                +"|";
                    }
                    path = path.substring(0,path.length()-1);
                    sendImage(path,"1");
                    for (int i = 0; i < paths.size(); i++) {
                        PhotoModel photoModel = new PhotoModel();
                        photoModel.setOriginalPath(paths.get(i));
                        photoModel.setChecked(true);
                        single_photos.add(photoModel);
                    }
                    if (img_uri.size() < 3) {
                        img_uri.add(null);
                    }
                    gridImgsAdapter.notifyDataSetChanged();
                }
                break;
            case 1001:
                if (data != null) {
                    List<String> paths = (List<String>) data.getExtras().getSerializable("photos");
                    if (file_uri.size() > 0) {
                        file_uri.remove(file_uri.size() - 1);
                    }
                    for (int i = 0; i < paths.size(); i++) {
                        file_uri.add(new UploadGoodsBean(paths.get(i), false));
                        //上传参数
                        path2 = path2 +CommonUtil.bitmapToBase64(BitmapHelper.getImage(paths.get(i), 200))
                                +"|";
                    }
                    path2 = path2.substring(0,path2.length()-1);
                    sendImage(path2,"1");
                    for (int i = 0; i < paths.size(); i++) {
                        PhotoModel photoModel = new PhotoModel();
                        photoModel.setOriginalPath(paths.get(i));
                        photoModel.setChecked(true);
                        single_photos.add(photoModel);
                    }
                    if (file_uri.size() < 9) {
                        file_uri.add(null);
                    }
                    gridFileAdapter.notifyDataSetChanged();
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private void sendImage(String img,String stallType){
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP_UpImg, LrConstant.POST);
            mRequest.add("action", "FileUploadImage");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("type", stallType);
            mRequest.add("img", img);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<UpImgM>(baseContext, true, null) {
                        @Override
                        public void doWork(UpImgM data, String code) {
                            LogUtils.e("c1111");
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (TextUtils.equals("1", code)) {
                                    if (upTag.equals("1")) {
                                        String url = obj.getString("data");
                                        String[] arr = url.split(",");
                                        for (int i = 0; i < arr.length; i++) {
                                            urlArray.add(arr[i]);
                                        }
                                        path = "";
                                    } else if (upTag.equals("2")) {
                                        String url = obj.getString("data");
                                        String[] arr = url.split(",");
                                        for (int i = 0; i < arr.length; i++) {
                                            fileArray.add(arr[i]);
                                        }
                                        path2 = "";
                                    }

                                } else {
                                    CommonUtil.showToask(baseContext, obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }
}
